package com.pig4cloud.pig.module.controller.product;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.DateUtils;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.mer.Mer;
import com.pig4cloud.pig.module.api.entity.platform.PlatformSplit;
import com.pig4cloud.pig.module.api.entity.product.Product;
import com.pig4cloud.pig.module.api.entity.product.ProductImg;
import com.pig4cloud.pig.module.api.entity.product.ProductType;
import com.pig4cloud.pig.module.api.entity.titleMenu.TitleMenuSectionLinks;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.mer.IMerService;
import com.pig4cloud.pig.module.service.platform.IPlatformSplitService;
import com.pig4cloud.pig.module.service.product.IProductEstateService;
import com.pig4cloud.pig.module.service.product.IProductImgService;
import com.pig4cloud.pig.module.service.product.IProductService;
import com.pig4cloud.pig.module.service.product.IProductTypeService;
import com.pig4cloud.pig.module.service.titleMenu.ITitleMenuSectionLinksService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.*;

/**
 * 商品Controller
 *
 * @author ruoyi
 * @date 2021-08-11
 */
@Validated
@Api(value = "商品控制器", tags = {"商品管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/product")
public class ProductController {

    private final IProductService productService;
	private final IProductImgService productImgService;
    private final ITitleMenuSectionLinksService titleMenuSectionLinksService;
	private final IProductEstateService productEstateService;
	private final IProductTypeService productTypeService;
	private final IEstateService estateService;
	private final IPlatformSplitService platformSplitService;
//	private final ISysDictDataService sysDictDataService;
	private final IMerService merService;

	@Value("${ruoyi.imgUrl}")
	private String imgUrl;

//	@Value("${ruoyi.imgUrlOss}")
//	private String imgUrlOss;

	@Value("${ruoyi.profile}")
	private String uploadPath;

	/**
     * 查询商品列表
     */
    @ApiOperation("查询商品列表")
    @PreAuthorize("@pms.hasPermission('module:product:list')")
    @GetMapping("/list")
    public TableDataInfo<Product> list(@Validated Product product) {
    	Map<String,Object> map = new HashMap<>();
        QueryWrapper<Product> qw = new QueryWrapper<>();
		if(product.getMerId() != null){
			qw.eq("mer_id",product.getMerId());
			map.put("mer_id",product.getMerId());
		}
		if(product.getIsCoupon() != null){
			qw.eq("is_coupon",product.getIsCoupon());
			map.put("is_coupon",product.getIsCoupon());
		}
        if(product.getCateId() != null){
            qw.eq("cate_id",product.getCateId());
			map.put("cate_id",product.getCateId());
        }
		if(product.getCateChildId() != null){
			qw.eq("cate_child_id",product.getCateChildId());
			map.put("cate_child_id",product.getCateChildId());
		}
		if(product.getIsDel()!=null){
			qw.eq("is_del",product.getIsDel());
			map.put("is_del",product.getIsDel());
		}
        if(StrUtil.isNotEmpty(product.getStoreName())){
			qw.like("store_name",product.getStoreName());
			map.put("store_name",product.getStoreName());
		}
		if(product.getIsShow() !=null){
			qw.eq("is_show",product.getIsShow());
			map.put("is_show",product.getIsShow());
		}
		if(product.getIsActive()!=null){
			qw.eq("is_active",product.getIsActive());
			map.put("is_active",product.getIsActive());
			if(product.getIsActive() == 1){
				qw.ge("active_end_time", DateUtils.getDateTimeByDayCountBefore(5));
				map.put("active_end_time", DateUtils.getDateTimeByDayCountBefore(5));
			}
		}
        if(product.getSectionId() != null){
            //添加内容行内的商品  排除已经添加上的
            QueryWrapper<TitleMenuSectionLinks> qwLinks = new QueryWrapper<>();
            qwLinks.eq("section_id",product.getSectionId());
            qwLinks.eq("link_type","product");
            List<TitleMenuSectionLinks> links = titleMenuSectionLinksService.list(qwLinks);
            List<Integer> ids = new ArrayList<>();
            if(CollUtil.isNotEmpty(links)){
                for (TitleMenuSectionLinks link : links){
                    if(link.getLinkId()!=null){
                        ids.add(link.getLinkId());
                    }
                }
                qw.notIn("id",ids);
            }
			map.put("linkIds", ids);
        }
        if(product.getOrderSort()!=null && product.getOrderSort() == 1){
        	qw.orderByAsc("active_end_time");
		}

		TableDataInfo<Product> td = PageUtils.buildDataInfo(productService.selectPageList(PageUtils.buildPage(),map));
        List<Product> list = td.getData();
        if(CollUtil.isNotEmpty(list)){
        	list.forEach(product1 -> {
				if(StrUtil.isNotEmpty(product1.getImage())){
					if(StrUtil.isNotEmpty(product1.getImage()) && product1.getImage().indexOf("http") < 0){
						product1.setImagePath(imgUrl + product1.getImage());
					}else{
						product1.setImagePath(product1.getImage());
					}
				}else{
					product1.setImagePath("");
				}

				if(StrUtil.isNotEmpty(product1.getQrCode())){
					product1.setQrCode(imgUrl + product1.getQrCode());
				}

				List<String> sliderImageArray = new ArrayList<>();
				product1.setSliderImageArray(sliderImageArray);
				if(StrUtil.isNotEmpty(product1.getSliderImage())){
					String[] sliderImages = product1.getSliderImage().split(",");
					for (String img: sliderImages){
						if(StrUtil.isNotEmpty(img) && img.indexOf("http") < 0){
							sliderImageArray.add(imgUrl + img);
						}else{
							sliderImageArray.add(img);
						}
					}
					product1.setSliderImageArray(sliderImageArray);
				}
			});
		}
        Map<String,Object> otherData = new HashMap<>();
        if(product.getMerId()!=null){
        	Mer mer  = merService.getById(product.getMerId());
			otherData.put("mer",mer);
		}
		td.setOtherData(otherData);
        return td;
    }

	/**
	 * 获取商品详细信息
	 */
	@ApiOperation("获取商品详细信息")
	@PreAuthorize("@pms.hasPermission('module:product:query')")
	@GetMapping("/listByMer/{merId}")
	public R listByMer(@PathVariable("merId") Long merId) {
		QueryWrapper<Product> qw = new QueryWrapper<>();
		qw.eq("mer_id",merId);
		qw.eq("is_coupon",0);
		List<Product> list = productService.list(qw);
		for (Product product1 : list){
			if(StrUtil.isNotEmpty(product1.getImage())){
				if(StrUtil.isNotEmpty(product1.getImage()) && product1.getImage().indexOf("http") < 0){
					product1.setImagePath(imgUrl + product1.getImage());
				}else{
					product1.setImagePath(product1.getImage());
				}
			}else{
				product1.setImagePath("");
			}

			ProductType productType = productTypeService.findById(product1.getCateChildId());
			if(productType!=null){
				product1.setCateChildName(productType.getTypeName());
			}

			if(StrUtil.isNotEmpty(product1.getQrCode())){
				product1.setQrCode(imgUrl + product1.getQrCode());
			}

			List<String> sliderImageArray = new ArrayList<>();
			product1.setSliderImageArray(sliderImageArray);
			if(StrUtil.isNotEmpty(product1.getSliderImage())){
				String[] sliderImages = product1.getSliderImage().split(",");
				for (String img: sliderImages){
					if(StrUtil.isNotEmpty(img) && img.indexOf("http") < 0){
						sliderImageArray.add(imgUrl + img);
					}else{
						sliderImageArray.add(img);
					}
				}
				product1.setSliderImageArray(sliderImageArray);
			}
		}
		return R.ok(list);
	}


	/**
	 * 重置二维码
	 */
	@SysLog("重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@pms.hasPermission('module:product:edit')")
	public R<Void> resetQrCode(@RequestBody Product product) {
		if(product.getId()!=null){
			try{
				product = productService.getById(product.getId());
				if(product != null){
					if(StrUtil.isEmpty(product.getProductNo())){
						String no = String.valueOf(2200000 + product.getId());
						product.setProductNo(no);
					}

					String qrCode = "";
					String fileName = "product_qr_" + product.getId() + ".jpg";
					String content = "https://www.sdyuedou.com/wxmini/produ/detail?id=" + product.getId();
					int upload_type = 0;//FileUploadUtils.TYPE_PRODUCT_QRCODE;
					System.out.println("content:  "+ content);
					String img_key = "";// FileUploadUtils.getUploadPrefix(upload_type) + fileName;
					QRCodeUtilEx.createQrCodeImg(content, "No." + product.getProductNo(), null, uploadPath + "/" + img_key, true, fileName, upload_type);
					qrCode = img_key;
					product.setQrCode(qrCode);
				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (productService.updateById(product)) {
				return R.ok();
			}
		}
		return R.failed();
	}


	/**
     * 获取商品详细信息
     */
    @ApiOperation("获取商品详细信息")
    @PreAuthorize("@pms.hasPermission('module:product:query')")
    @GetMapping("/{id}")
    public R<Product> getInfo(@PathVariable("id") Long id) {
    	Product product = productService.goodsDetail(id);
    	if(product!=null){
    		if(product.getIsActive() == 1){
    			if(product.getActiveBeginTime()!=null && product.getActiveEndTime() !=null){
					String[] dateRange = {  DateUtils.getDate(product.getActiveBeginTime()),  DateUtils.getDate(product.getActiveEndTime()) };
					product.setActiveDateRange(dateRange);
				}
			}


    		QueryWrapper<ProductImg> qwImg = new QueryWrapper<>();
			qwImg.eq("product_id",product.getId());
			qwImg.eq("img_type",0);
			List<ProductImg> images = productImgService.list(qwImg);
			for (ProductImg img : images){
				if(StrUtil.isNotEmpty(img.getImgUrl())){
					img.setImgUrlPath(imgUrl + img.getImgUrl());
				}
			}
			product.setProductImgs(images);



			String lunboImgs = "";
			QueryWrapper<ProductImg> qwLunbo = new QueryWrapper<>();
			qwLunbo.eq("product_id",product.getId());
			qwLunbo.eq("img_type",1);
			List<ProductImg> lunbos = productImgService.list(qwLunbo);
			for (ProductImg img : lunbos){
				if(StrUtil.isNotEmpty(img.getImgUrl())) {
					lunboImgs += imgUrl + img.getImgUrl() + ",";
					img.setImgUrlPath(imgUrl + img.getImgUrl());
				}
			}
			product.setProductImgLunbos(lunbos);

			if(StrUtil.isNotEmpty(lunboImgs)){
				lunboImgs = lunboImgs.substring(0,lunboImgs.length() - 1);
			}

			product.setSliderImagePath(lunboImgs);
		}
        return R.ok(product);
    }

	/**
	 * 获取商品详细信息
	 */
	@ApiOperation("获取添加商品用到的数据")
	@PreAuthorize("@pms.hasPermission('module:product:query')")
	@GetMapping("/goAddData")
	public R goAddData() {
		Map<String,Object> map = new HashMap<>();
		List<Estate> estates = estateService.list(new LambdaQueryWrapper<Estate>().eq(Estate::getState,0));
		List<PlatformSplit> splits = platformSplitService.list();
		splits.forEach(split->{
//			SysDictData dictData = sysDictDataService.selectDictData("split_type",split.getSplitType());
//			String content = "：业主：" + split.getProprietorSplit() + split.getSplitTypeUnit();
//			content += ", 物业：" + split.getPropertySplit() + split.getSplitTypeUnit();
//			content += "，平台：" + split.getPlatformSplit() + split.getSplitTypeUnit();
//			if (dictData!=null){
//				split.setSplitTypeName(dictData.getDictLabel() + content);
//				split.setSplitTypeUnit(dictData.getCssClass());
//			}
		});

		map.put("estates",estates);
		map.put("splits",splits);
		return R.ok(map);
	}


	@ApiOperation(value = "生成属性")
	@PostMapping(value = "/isFormatAttr/{id}/{isReset}")
	public R isFormatAttr(@PathVariable("id") Long id,@PathVariable("isReset") Integer isReset, @RequestBody String jsonStr){
		return R.ok(productService.getFormatAttr(id,jsonStr,false,isReset));
	}


	/**
	 * 修改 热门状态
	 */
	@PreAuthorize("@pms.hasPermission('module:product:edit')")
	@SysLog("修改 热门状态")
	@PutMapping("/handleIshotChange")
	public R handleIshotChange(@RequestBody Product product) {
		return R.okByRow(productService.updateById(product));
	}

	/**
	 * 修改抖音上下架状态
	 */
	@PreAuthorize("@pms.hasPermission('module:product:edit')")
	@SysLog("修改抖音上下架状态")
	@PutMapping("/changeShowDyStatus")
	public R changeShowDyStatus(@RequestBody Product product) {
		return R.okByRow(productService.updateById(product));
	}

	/**
	 * 修改售罄状态
	 */
	@PreAuthorize("@pms.hasPermission('module:product:edit')")
	@SysLog("修改售罄状态")
	@PutMapping("/changeSaleOutStatus")
	public R changeSaleOutStatus(@RequestBody Product product) {
		return R.okByRow(productService.updateById(product));
	}





    /**
     * 新增商品
     */
    @ApiOperation("新增商品")
    @PreAuthorize("@pms.hasPermission('module:product:add')")
    @SysLog("商品")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody Product product) {
		int ret = 0;
		try{
			if(product.getIsActive() == 1 && product.getActiveDateRange()!=null){
				String[] dateRange = product.getActiveDateRange();
				Date freeBeginTime = DateUtils.parseDate( dateRange[0] + " 00:00:00");
				Date freeEndTime = DateUtils.parseDate( dateRange[1] + " 23:59:59");
				product.setActiveBeginTime(freeBeginTime);
				product.setActiveEndTime(freeEndTime);
			}
			product.setCreateTime(new Date());
			product.setIsUseIntegral(0);

			ret = productService.addProduct(product);
			if(ret == -1){
				return R.failed("请上传轮播图");
			}
		}catch (Exception e){
			e.printStackTrace();
		}
		return R.okByRow(ret);
    }

    /**
     * 修改商品
     */
    @ApiOperation("修改商品")
    @PreAuthorize("@pms.hasPermission('module:product:edit')")
    @SysLog("商品")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody Product product) {
    	int ret = 0;
    	try{

			if(product.getIsActive() == 1 && product.getActiveDateRange()!=null){
				String[] dateRange = product.getActiveDateRange();
				Date freeBeginTime = DateUtils.parseDate( dateRange[0] + " 00:00:00");
				Date freeEndTime = DateUtils.parseDate( dateRange[1] + " 23:59:59");
				product.setActiveBeginTime(freeBeginTime);
				product.setActiveEndTime(freeEndTime);
			}
			ret = productService.addProduct(product);

			if(ret == -1){
				return R.failed("请上传轮播图");
			}

		}catch (Exception e){
    		e.printStackTrace();
		}
        return R.okByRow(ret);
    }


	/**
	 * 修改商品
	 */
	@ApiOperation("修改商品")
	@PreAuthorize("@pms.hasPermission('module:product:edit')")
	@SysLog("商品")

	@PutMapping("/num")
	public R<Void> num(@Valid @RequestBody Product product) {
		return R.okByRow(productService.updateById(product) ? 1 : 0);
	}

    /**
     * 删除商品
     */
    @ApiOperation("删除商品")
    @PreAuthorize("@pms.hasPermission('module:product:remove')")
    @SysLog("商品")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空") @PathVariable Long[] ids) {
		boolean bl = false;
		for(Long id : ids){
    		Product product = productService.findById(id);
    		if(product!=null){
    			product.setIsDel(1);
				bl = productService.updateById(product);
				if(bl){
					return R.okByRow(bl?1 :0);
				}
			}
		}
		return R.okByRow(bl?1 :0);
    }

	@ApiOperation("删除商品")
	@PreAuthorize("@pms.hasPermission('module:product:remove')")
	@SysLog("商品")
	@DeleteMapping("/remove2/{ids}")
	public R<Void> remove2(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
		return R.okByRow(productService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
	}

	@ApiOperation("查询商品列表")
	@PreAuthorize("@pms.hasPermission('module:product:list')")
	@GetMapping("/showList")
	public List<Product> showList(@Validated Product product) {
		QueryWrapper<Product> qw = new QueryWrapper<>();
		if (ObjectUtil.isNotEmpty(product.getMerId())){
			qw.eq("mer_id",product.getMerId());
		}
		if (ObjectUtil.isNotEmpty(product.getCateId())){
			qw.eq("cate_id",product.getCateId());
		}
		TableDataInfo<Product> td = PageUtils.buildDataInfo(productService.page(PageUtils.buildPage(),qw));
		List<Product> list = td.getData();
		for (Product list1:list){
			list1.setImage(imgUrl+list1.getImage());
		}
		return list;
	}
}
